<template>
	<!-- 中药房库存盘点数据 -->
	<div class="LocationCatalog">
		<!-- main -->
		<div class="main">
			<el-tabs v-model="activeName" @tab-click="handleClick">
			    <el-tab-pane label="中药房库存盘点数据" name="first">
					<!-- right -->
					<div class="main-right">
						<!-- tit -->
						<div class="main-icon">
							<div class="main-icon-a">
								<i :class="iconComes" style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;;background-color: #00aaff;color: #fff;"></i>
								<span style="font-size: 16px;font-weight:300;margin-left: 12px;color: #606266;">{{ CatalogueName }}</span>
							</div>
							<!-- btn1 -->
							<div class="main-icon-b">
								<span style="font-size: 12px;color: #606266;font-weight: bold;">库房名称：</span>
								<el-dropdown @command="handleCommand" trigger="click">
									<span class="el-dropdown-link">{{ DropDownedName }}<i class="el-icon-down"></i></span>
									<el-dropdown-menu slot="dropdown">
									  <el-dropdown-item command="a">中药房</el-dropdown-item>
									</el-dropdown-menu>
								</el-dropdown>
							</div>
							<!-- btn2 -->
							<div class="main-icon-c">
								<span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">盘点日期：</span>
								<el-date-picker v-model="pdDate" type="daterange" align="right" size="mini" unlink-panels 
								range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
								</el-date-picker>
							</div>
							<!-- btn3 -->
							<div class="main-icon-c">
								<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="handClick(i)">{{ v.title }}</el-button>
							</div>
						</div>
						<!-- table -->
						<div class="table">
							<el-table :data="tableData" border @row-dblclick="handledbRow" :style="{ width: windowWidth + 'px' }"
							element-loading-text="数据加载中..." v-loading="loading" element-loading-spinner="el-icon-refresh"
							highlight-current-row @current-change="handleCurrentTableChange">
								<el-table-column label="系统序号" prop="id" width="88"></el-table-column>
								<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
								<!-- edit -->
								<el-table-column fixed="right" label="操作" width="88">
								  <template slot-scope="scope">
									  <div class="editbox" style="text-align: center;">
										<el-button type="text" @click="editFormValue(scope.row)" size="mini">编辑</el-button>
										<el-button type="text" @click="handleDelete(scope.row.id)" size="mini">删除</el-button>
									  </div>
								  </template>
								</el-table-column>
								<!-- fixed -->
								<el-table-column fixed="left" label="行号" type="index" width="50"></el-table-column>
							</el-table>
							<!-- <span v-if="noData"> {{ noData }} </span> -->
						</div>
						<!-- feet -->
						<div class="feet" id="feet">
							<!-- 分页 -->
							<el-pagination
							style="margin: 12px;"
							@size-change="handleSizeChange"
							@current-change="handleCurrentChange"
							:current-page="pageNum"
							:page-sizes="[20,50,100]"
							:page-size="pageSize"
							:total="totalSize"
							layout="total, sizes, prev, pager, next, jumper"
							background
							>
							</el-pagination>
							<div class="feetBtn">
								<!-- btn3 -->
								<el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="small" plain
									@click="feetHandClick(i)" style="margin-left: 12px;">{{ v.title }}
								</el-button>
							</div>
						</div>
					</div>
				</el-tab-pane>
				<!-- 中药房不可盘点数据 -->
			    <el-tab-pane label="中药房不可盘点数据" name="second">
					<!-- table -->
					<div class="untable">
						<el-table :data="untableData" border @row-dblclick="handledbRow" :style="{ width: windowWidth + 'px' }"
						element-loading-text="数据加载中..." v-loading="loading" element-loading-spinner="el-icon-refresh"
						highlight-current-row @current-change="handleCurrentTableChange">
							<el-table-column label="系统序号" prop="id" width="88"></el-table-column>
							<el-table-column v-for="(col, inx) in untableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
							<!-- edit -->
							<el-table-column fixed="right" label="操作" width="88">
							  <template slot-scope="scope">
								  <div class="editbox" style="text-align: center;">
									<el-button type="text" @click="editFormValue(scope.row)" size="mini">编辑</el-button>
									<el-button type="text" @click="handleDelete(scope.row.id)" size="mini">删除</el-button>
								  </div>
							  </template>
							</el-table-column>
							<!-- fixed -->
							<el-table-column fixed="left" label="行号" type="index" width="50"></el-table-column>
						</el-table>
						<!-- <span v-if="noData"> {{ noData }} </span> -->
					</div>
					<!-- feet -->
					<div class="feet" id="feet">
						<!-- 分页 -->
						<el-pagination
						style="margin: 12px;"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="pageNum"
						:page-sizes="[20,50,100]"
						:page-size="pageSize"
						:total="totalSize"
						layout="total, sizes, prev, pager, next, jumper"
						background
						>
						</el-pagination>
						<div class="feetBtn">
							<!-- btn3 -->
							<el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="small" plain
								@click="feetHandClick(i)" style="margin-left: 12px;">{{ v.title }}
							</el-button>
						</div>
					</div>
				</el-tab-pane>
			</el-tabs>
			
		</div>
		
		<!-- add dialog -->
		<div class="addDiglog">
			<addCountDiglog ref='sonRef' @untable-data="handleUntableData" :parent-method="loadData"></addCountDiglog>
		</div>
		<!-- 打印设置对话框 -->
<!-- 		<print-settings-dialog 
		  :visible.sync="printDialogVisible" 
		  :content="printContent"
		/> -->
			
	</div>
</template>

<script>
	// selfs / js
	// import LocationCatalog from '@/external/LocationCatalog.js'
	//  selfs / props
	import addCountDiglog from './addCount.vue'
	// import PrintSettingsDialog from '@/components/PrintSettingsDialog.vue';
	// 接口
	// import { skPage } from "@/api/systemCatalogue/Western.js";
	import { skPage } from "@/api/MedicenHouse/traMedici.js";
	
	export default {
		inject: ['reload'], // 无痕刷新
		components: {
			addCountDiglog
		},
		data() {
			return {
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				// str
				toCode:'',
				startTime:'',
				endTime:'',
				activeName:'first',
				pdDate:'', // 盘点日期
				windowWidth: '', //表格自适应宽度
				CatalogueName:'【中药房】库存盘点',
				DropDownedName:'【中药房】库存盘点',
				iconComes:'el-icon-yllb',
				// boolean
				loading:false,
				disabled:true,
				printDialogVisible: false,
				// showChild:false, // 控制子组件挂载
				// number
				pageNum: 1, //当前页currentPage
				pageSize: 8,
				totalSize: 10, //总条数
				pageSizeSave:0,
				// arr
				form: {},
				editform:{},
				currentTable:[],
				// title右侧按钮
				headerBtn:[
					{ title:"刷新", type:"", icon:"el-icon-refresh", loading:false}, { title:"高级", type:"primary", icon:"", loading:false},
				],
				feetBtn:[
				 { refesh:"refesh", title:"新增", type:"primary", icon:"el-icon-plus" },
				 { refesh:"refesh", title:"删除", type:"primary", icon:"el-icon-s-claim" },
				 { refesh:"refesh", title:"草稿录入", type:"primary", icon:"el-icon-document-checked" },
				 { refesh:"refesh", title:"合并提交", type:"primary", icon:"el-icon-sort" },
				 { refesh:"refesh", title:"审核", type:"primary", icon:"el-icon-printer" },
				 { refesh:"refesh", title:"结转", type:"primary", icon:"el-icon-upload2" },
				 { refesh:"refesh", title:"查看", type:"primary", icon:"el-icon-printer" },
				 { refesh:"refesh", title:"打印", type:"primary", icon:"el-icon-upload2" },
				 { refesh:"refesh", title:"关闭", type:"primary", icon:"el-icon-close" },
				 ],
				// tableRows
				tableRows:[
					{ name:"状态", prop:"status"},{ name:"单据编号", prop:"docNum"},
					{ name:"盘点日期", prop:"skDate"},{ name:"库房名称", prop:"shedName"},
					{ name:"账面成本金额", prop:"bookAmt" },{ name:"实存成本金额", prop:"aeAmt"},
					{ name:"账面零售金额", prop:"bookSaleAmt"},{ name:"实存零售金额", prop:"costProfitAmt"},
					{ name:"成本盈亏金额", prop:"costProfitAmt", },{ name:"零售盈亏金额", prop:"retailProfitAmt"},
					{ name:"建立人", prop:"createId"},{ name:"建立时间", prop:"createTime" },
					{ name:"合并人", prop:"mergeId"},{ name:"合并时间", prop:"mergeTime" },
					{ name:"审核人", prop:"createId" },{ name:"审核时间", prop:"createTime"},
					{ name:"过单人", prop:"passingOrdersId"},{ name:"过单时间", prop:"passingOrdersTime"},
					{ name:"冲销人", prop:"nullifyId"},{ name:"冲销时间", prop:"nullifyTime"},
					{ name:"备注", prop:"remark"},
				],
				// tableRows
				untableRows:[
					{ name:"数据表", prop:"docType" },{ name:"状态", prop:"state" },
					{ name:"单据编号", prop:"docNum" },{ name:"库房名称", prop:"shedId" },
					{ name:"盘点日期", prop:"" },{ name:"制单人", prop:"createId" },
					{ name:"制单时间", prop:"createTime" },{ name:"审核人", prop:"pacCnt" },
					{ name:"审核时间", prop:"pacUnt" },{ name:"隶属机构", prop:"pacCnt" },
					{ name:"备注", prop:"remake" }
				],
				tableData: [],
				untableData:[],
				pickerOptions: {
				  shortcuts: [{
					text: '最近一周',
					onClick(picker) {
					  const end = new Date();
					  const start = new Date();
					  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
					  picker.$emit('pick', [start, end]);
					}
				  }, {
					text: '最近一个月',
					onClick(picker) {
					  const end = new Date();
					  const start = new Date();
					  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
					  picker.$emit('pick', [start, end]);
					}
				  }, {
					text: '最近三个月',
					onClick(picker) {
					  const end = new Date();
					  const start = new Date();
					  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
					  picker.$emit('pick', [start, end]);
					}
				  }]
				},
			};
		},
		computed: {
		   
		},
		mounted() {
			// 数据源
			this.loadData();
			//获取动态盒子宽度，实时赋值给右侧 =i> this.$refs.mainRight.offsetWidth;
			this.$nextTick(()=>{
				this.updateWindowWidth();
				window.addEventListener('resize', this.updateWindowWidth);
			});
		},
		methods: {
			/*
				数据源
			*/
			async loadData(){
				let res = await skPage({
					condtion:this.condtion,
					status:this.status,
					startTime:this.startTime,
					endTime:this.endTime,
					pageNum:this.pageNum,
					pageSize:this.pageSize,
				});
				if(res.code === 200){
					// console.log(res.data.content);
					this.tableData = res.data.content
					this.totalSize = res.data.totalSize
				}else{
					this.$message({ type: 'error', message: res.message });
					this.tableData = [];
				}
			},
			handleClick(tab, event) {
				console.log(tab, event);
			},
			// 处理不可盘点数据
			handleUntableData(res) {
				console.log(res,'jieksasdoada');
				if(res.code === 200){
					this.activeName = 'first';
					this.tableData.push(res.data);  // 将数据赋值给tableData
				}else if(res.code === 201){
					this.activeName = 'second';
					this.untableData = res.data;  // 将数据赋值给untableData
				}
				
				
			},
			// props
			feetHandClick(i){
				// i event
				switch (i) {
					case 0:
						// 新增
						this.nameTitle = '新增';
						this.$refs.sonRef.open(this.nameTitle)
					break;
					case 1:
						// 处理索引0的逻辑 => 删除
						if(this.currentTable.length === 0){
							this.$message({ type: 'warning', message: '请先单击选择一条数据'});
						}else if(this.currentTable.state != 0){
							this.$message({ type: 'error', message: '只能删除草稿数据！'});
						}else{
							this.$confirm("是否删除?", "提示", {
							  confirmButtonText: "确定",
							  cancelButtonText: "取消",
							  type: "warning",
							})
							.then(async() => {
								// 状态 => 删除
							}).catch(() => {
								this.$message({ type: "info",message: '已取消'});
							});
						}
					break;
					case 2:
					// 草稿录入 动态路径参数
					this.$router.push({ path: '/traMediciHouse/details', query: { id: this.currentTable.id  } })
					break;
					case 3:
					// 审核
					
					break;
					case 4:
					// 过单
					
					break;
					case 7:
					// 打印
					 this.printDialogVisible = true;
					break;
				}
			},
			handleDelete(rowId){
				console.log(rowId);
				this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(async() => {
					let ress = await deleteTP({
						id: rowId
					})
					if(res.code === 200){
						this.$message({type:'success',message:'已删除'});
						this.loadData();
					}else{
						this.$message.error(ress.message)
					}
				}).catch(() => {
				  this.$message({
					type: 'info',
					message: '已取消删除'
				  });          
				});
			},
			
			// 编辑保存
			saveEditData(){
				
			},
			
			/*
				选择框
			*/

			/*
				about input
			*/

			/*
				about table
			*/
		    // col 里面包含了表头字段和名称，list 是表格数据
		    columnWidth(col, list) {
		         let prop = col.prop,lab = col.lab;
		         let width = 20; // 设定一个最小值
		         let maxlenStr = ""; // 最长字符串
		         for (let info of list) {
		           if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		         }
		         width = Math.max(width, len(lab), len(maxlenStr));
		         // 表格自带的内边距(20px) 自调
		         return width + 12; // 这里加了 12px
		         function len(str) {
		           // 实际分配长度可根据需要自行调整
		           let length = 0;
		           for (const char of str + "") {
		             // 英文小写字符 8px
		             if ("a" <= char && char <= "z") length += 8;
		             // 英文大写字符 12px
		             else if ("A" <= char && char <= "Z") length += 12;
		             // 中文字符 16px
		             else if (char >= "\u4e00" && char <= "\u9fa5") length += 28;
		             // 其他 8px
		             else length += 8;
		           }
		           return length;
		         }
		    },
			// 新增等步骤
			handClick(i) {
				// i event
				switch (i) {
					case 0:// 处理索引1的逻辑 页面刷新
						this.loading = true;
						setTimeout(() => {
							this.reload();
							this.$message({type:'success',message:'已刷新'})
							this.loading = false;		
						}, 1500)
					break;
					case 1:
						// 处理索引2的逻辑
						this.$message({ type: "info", message: "暂不支持,请联系工作人员!"});
					break;
				}
			},
			// 表格单选
			handleCurrentTableChange(val){
				console.log(val);
				this.currentTable = val
			},
			// db events 双击表格行
			handledbRow(row, column, event){
				if(row){
					this.loading = true;
					setTimeout(()=>{
						console.log(row,'双击过后查看');
						// 使用点语法
						// res.data.watch = true;
						let param = {
							id:row.id,
							label:'查看',
							isShow:false,
							system:true,
						}
						this.loading = false;
						this.$refs.addModel.openAddModel(param);
					},888)
				} else { 
					this.$message({ type: "info", message: "未知异常，请稍后重试！"});
				}
			},
			handleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
					this.formdisabled = true;
					location.reload();
					done();
				  })
				  .catch(_ => {
					this.formdisabled = this.formdisabled;
				  });
			},
			handleCommand(command) {
			  // 这里的 command 就是你点击的菜单项的 command 属性值
			  // console.log(command);
			  // 根据 command 值执行相应的逻辑
			  switch (command) {
				case 'a':
				  // 处理a的逻辑
				  console.log('执行A逻辑');
				  this.DropDownedName = '中药房'
				  break;
				// ... 其他 case
			  }
			},
			// 拦截

			//分页
			//每页条数改变触发
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageNum = val;
				this.loadData();
			},
			//当前条数改变触发
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.pageNum = val;
				this.loadData();
			},
			// 实时宽度
			updateWindowWidth() {
			    this.windowWidth = window.innerWidth - 188;
			},
		}
	}
</script>

<style lang="less" scoped>
	.LocationCatalog {
		height: 100%;
		width: 100%;
		// table
		/deep/ .el-button{
			background-color: var(--primary-color, #409EFF) !important;
			color: var(--text-color, #304156) !important;
		}
		/deep/ .el-table .cell{
			font-size: 12px;
			text-overflow: ellipsis;
			white-space: nowrap;
			overflow: hidden;
		}
		/deep/ .el-table th{
			background-color: #f1f1f1;
			border: none;
			color: #2d2d2d;
		}
		// header
		.header {
			display: flex;
			flex-direction: row;
			align-items: center;
			height: 40px;
			background-color: #efefef;
			padding: 4px;

			// justify-content: space-evenly;
			// icon
			.header-icon {
				display: flex;
				align-items: center;
				justify-content: start;
				.header-btn{
					margin-left: 20px;
				}
			}

		}

		// main
		.main {
			width: 100%;
			display: flex;
			justify-content: left;
			padding: 4px;
			// right
			.main-right {
				width: 100%;
				height: 100%;
				// icon
				.main-icon {
					display: flex;
					align-items: center;
					line-height: 40px;
					.main-icon-a{
						// width: 240px;
						// background-color: #00557f;
					}
					.main-icon-b{
						margin-left: 28px;
						/deep/ .el-dropdown{
							font-size: 12px;
							cursor: pointer;
						}
						/deep/ .el-dropdown:hover {
							font-weight: bold;
							color: #66b1ff;
						}
						/deep/ .el-icon--right{
							// background-color: #66b1ff;
						}
						/deep/ .el-popper[x-placement^=bottom]{
							margin-top: 0;
						}
					}
					// c
					.main-icon-c{
						margin-left: 28px;
						display: flex;
						align-items: center;
					}
				}
				
				// table
				.table{
					/* 自定义高亮颜色 */
					::v-deep .el-table__body tr.current-row > td {
					  background-color: #00557f !important;
					  color: #f9f9f9; /* 可选：修改文字颜色 */
					}
					/deep/ .el-table .cell{
						font-size: 12px;
						text-align: center;
					}
				}
			}
		}
		.feet{
			height: 100px;
			width: 100%;
			padding: 12px;
			position: fixed;
			// top: 0;
			bottom: 10px;
			left: 168px;
			right: 0;
			.feetBtn{
				display: flex;
				justify-content: start;
				align-items: center;
				flex-wrap: wrap;
				gap: 8px;
			}
		}
	}
</style>